import editForm from "../form.vue";
import { handleTree } from "@/utils/tree";
import { message } from "@/utils/message";
import {
  addDict,
  clearDictCache,
  deleteDict,
  type Dict,
  getDictList,
  updateDict
} from "@/api/system";
import { addDialog } from "@/components/ReDialog";
import { h, onMounted, reactive, ref } from "vue";
import { DictTag } from "@/components/ReDict";
import { storageSession } from "@pureadmin/utils";

export function useDict() {
  const form = reactive({
    label: null,
    state: null
  });

  const formRef = ref();
  const dataList = ref([]);
  const loading = ref(true);
  const columns: TableColumnList = [
    {
      label: "字典名称",
      prop: "label",
      width: 200
    },
    {
      label: "字典标识",
      prop: "code",
      width: 200
    },
    {
      label: "字典编码",
      prop: "value",
      width: 150
    },
    {
      label: "字典描述",
      prop: "description",
      align: "center"
    },
    {
      label: "排序",
      prop: "sort",
      width: 100
    },
    {
      label: "状态",
      prop: "state",
      width: 100,
      cellRenderer: ({ row, props }) => (
        <DictTag size={props.size} value={row.state} code="State" />
      )
    },
    {
      label: "操作",
      fixed: "right",
      width: 230,
      align: "center",
      slot: "operation"
    }
  ];

  function resetForm(formEl: any) {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  }

  function onSearch() {
    getDictList(form)
      .then(data => {
        dataList.value = handleTree(data); // 处理成树结构
      })
      .catch(err => {
        message(`字典查询失败:${err.message}`, {
          type: "error"
        });
      })
      .finally(() => {
        setTimeout(() => {
          loading.value = false;
        }, 500);
      });
  }

  function openDialog(title = "新增", row?: Dict) {
    addDialog({
      title: `${title}字典`,
      props: {
        formInline: {
          id: row?.id ?? "",
          parentId: row?.parentId ?? undefined,
          label: row?.label ?? "",
          code: row?.code ?? "",
          value: row?.value ?? "",
          color: row?.color ?? "",
          description: row?.description ?? "",
          state: row?.state ?? true,
          sort: row?.sort ?? 1
        }
      },
      width: "40%",
      draggable: true,
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(editForm, { ref: formRef }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as Dict;
        function add() {
          addDict(curData)
            .then(() => {
              message("字典新增成功", {
                type: "success"
              });
              done(); // 关闭弹框
              onSearch(); // 刷新表格数据
            })
            .catch(err => {
              message(`字典新增失败:${err.message}`, {
                type: "error"
              });
            });
        }
        function update() {
          updateDict(curData)
            .then(() => {
              message("字典更新成功", { type: "success" });
              done(); // 关闭弹框
              onSearch(); // 刷新表格数据
            })
            .catch(err => {
              message(`字典更新失败:${err}`, { type: "error" });
            });
        }
        FormRef.validate((valid: boolean) => {
          if (valid) {
            // 表单规则校验通过
            if (title === "新增") {
              // 实际开发先调用新增接口，再进行下面操作
              add();
            } else {
              // 实际开发先调用编辑接口，再进行下面操作
              update();
            }
          }
        });
      }
    });
  }

  function handleDelete(row: Dict) {
    if (!row.isLeaf) {
      message("请先删除所有子字典后再删除上级字典", { type: "warning" });
      return;
    }
    deleteDict(row.id)
      .then(() => {
        message("字典删除成功", { type: "success" });
        onSearch();
      })
      .catch(err => {
        message(`字典删除失败:${err}`, { type: "error" });
      });
  }

  function clearCache() {
    clearDictCache()
      .then(() => {
        message("缓存刷新成功", { type: "success" });
        storageSession().clear();
      })
      .catch(err => {
        message(`缓存刷新失败:${err}`, { type: "error" });
      });
  }

  onMounted(() => {
    onSearch();
  });

  return {
    form,
    loading,
    columns,
    dataList,
    /** 搜索 */
    onSearch,
    /** 重置 */
    resetForm,
    /** 新增、编辑字典 */
    openDialog,
    /** 删除字典 */
    handleDelete,
    clearCache
  };
}
